#include "cxgrabthread.h"
#include <QTime>
using namespace std;
CxGrabThread::CxGrabThread(dc1394camera_t *device, CxImageBuffer<4> *pbuffer, QObject *parent) :
    QThread(parent),
    m_pbuffer(pbuffer),
    m_pcamera(device),
    m_outerSpin(true),m_innerSpin(false)
{
}


void            CxGrabThread::grabStart()
{

    dc1394error_t       error;
    dc1394switch_t      pswitch;
    dc1394video_mode_t  mode;
    dc1394framerate_t   rate;

    error   =   dc1394_video_get_transmission(m_pcamera,&pswitch);
    printError(error);

    if(pswitch)
        grabExit();

    error   =   dc1394_capture_setup(m_pcamera,4,DC1394_CAPTURE_FLAGS_DEFAULT);
    printError(error);

    error   =   dc1394_video_set_transmission(m_pcamera,DC1394_ON);
    printError(error);

    error   =   dc1394_video_get_mode(m_pcamera,&mode);
    printError(error);

    error   =   dc1394_get_image_size_from_video_mode(m_pcamera,mode,&width,&height);
    printError(error);

    error   =   dc1394_video_get_framerate(m_pcamera,&rate);
    printError(error);


    m_outerSpin=true;
    m_innerSpin=true;
    start();
    msleep(40);
    m_pauseCond.wakeOne();
}



void            CxGrabThread::grabExit()
{
    m_innerSpin=false;

    dc1394error_t   error;
    dc1394switch_t  pswitch;

    error   =   dc1394_video_get_transmission(m_pcamera,&pswitch);
    printError(error);

    if(pswitch)
    {
        error   =   dc1394_video_set_transmission(m_pcamera,DC1394_OFF);
        printError(error);
    }

    m_outerSpin=false;
}

void            CxGrabThread::slot_start()
{
    grabStart();
}

void            CxGrabThread::slot_exit()
{
    grabExit();
}

void            CxGrabThread::slot_pause()
{
    m_innerSpin=false;
}

void            CxGrabThread::slot_continue()
{
    m_innerSpin=true;
    m_pauseCond.wakeOne();
}

void        CxGrabThread::run()
{
    dc1394video_frame_t     *frame;
    dc1394error_t       error;

    static QTime time;

    while(m_outerSpin)
    {
        QMutexLocker    locker(&m_mu);
        m_pauseCond.wait(&m_mu);

        while(m_innerSpin)
        {
            if(m_pcamera==NULL)
                 grabExit();

            time.restart();

            error = dc1394_capture_dequeue(m_pcamera,DC1394_CAPTURE_POLICY_WAIT,&frame);
            printError(error);

            m_pbuffer->push_image(frame->image,width,height,frame->color_coding);

            error = dc1394_capture_enqueue(m_pcamera,frame);
            printError(error);
        }
    }
}




